const express = require('express');

const { User } = require('./models/db');

const jwt = require('jsonwebtoken');

const app = express();

const SECRET = 'sajkFAjscbhsafchdsvjkks';

app.use(express.json());

app.get('/api', async(req, res) => {
    const user = await User.find();
    res.send(user);
    // res.send('ok');
})

app.post('/api/register', async(req, res) => {
    const user = await User.create({
        username: req.body.username,
        password: req.body.password
    })
    res.send(user);
    // console.log(req.body);
});

app.post('/api/login', async(req, res) => {
    const user = await User.findOne({ username: req.body.username });
    if (!user) {
        return res.status(422).send({
            message: '用户名不存在'
        })
    }
    const isPasswordValid = require('bcryptjs').compareSync(req.body.password, user.password);
    if (!isPasswordValid) {
        return res.status(422).send({
            message: '密码错误'
        });
    }
    // 生成token
    const token = jwt.sign({
        id: String(user._id)
    }, SECRET)
    res.send({
            user,
            token
        })
        // res.send(isPasswordValid);
        // res.send(user);
});

const auth = async(req, res, next) => {
    const raw = String(req.headers.authorization.split(' ').pop());
    const { id } = jwt.verify(raw, SECRET);
    req.user = await User.findById(id);
    next()
}

app.get('/api/profile', auth, async(req, res) => {
    res.send(req.user);
})

app.listen(3001, () => {
    console.log('http://localhost:3001');
})